from base import ZooKeeperUtil, ToolUtil, get_service_list, get_info_error
from flask import Flask, request, redirect, url_for, render_template
import logging

app = Flask(__name__)
# 实例化工具包
tool = ToolUtil()


# 获取dubboAPI列表页面
@app.route('/', methods=['POST', 'GET'], strict_slashes=False)
def page_show_dubbo():
    # 实例化zk对象
    with ZooKeeperUtil() as zk:
        service_list = get_service_list(zk)
        if request.method == 'POST':
            info, error = get_info_error(zk, request.form['service'])
            return render_template('dubbo.html', info=info, res=error, services=service_list)
        return render_template('dubbo.html', services=service_list)


# 请求dubbo接口获取结果页面
@app.route('/dubbo/invoke', methods=['POST', 'GET'])
def page_dubbo_invoke():
    if request.method == 'POST':
        data = {
            'service': request.form['service'],
            'method': request.form['method'],
            'args': request.form['args']
        }
        res, info = tool.dubbo_client(
            data['service'], data['method'], data['args'])
        return render_template('dubbo.html', res=res, req=data, info=info)
    return redirect(url_for('page_show_dubbo'))


# 本地调试dubbo接口页面
@app.route('/local', methods=['POST', 'GET'])
def page_dubbo_invoke_local():
    return render_template('local.html')


# 本地调试dubbo接口 api接口
@app.route('/dubbo/request', methods=['POST'])
def api_dubbo_request():
    data = request.form
    res = tool.dubbo_request(data['host'], data['port'], data['service'], data['method'], data['args'])
    return {'code': 200, 'msg': '操作成功', 'obj': res}


# 启动相关
app.jinja_env.auto_reload = True
app.config['TEMPLATES_AUTO_RELOAD'] = True
logging.getLogger('werkzeug').setLevel(logging.ERROR)
if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)